/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package lottoapp;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.Transient;
import org.simpleframework.xml.core.Persister;
/**
 *
 * @author Mark Dechamps
 */
public class LottoAppModel {

    @Transient
    private static File file = new File("lotto.xml");

    
    @ElementList
    private Set<Player> players;
    @ElementList
    private Set<LottoResult> result=new HashSet<>();
    @Transient
    private static LottoAppModel model;
    
    public static LottoAppModel getInstance() {
        return model;
    }
    
     
    public LottoAppModel() {
        players=new HashSet<>();
        result =  new HashSet<>();
    }

    public Set<Player> getPlayers() {
        return players;
    }

    public Set<LottoResult>  getResult() {
        return result;
    }

    public void setPlayers(Set<Player> players) {
        this.players = players;
    }

    public void setResult(Set<LottoResult> result) {
        this.result = result;
    }

    
    
    public static LottoAppModel load(){
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException ex) {
                Logger.getLogger(LottoAppModel.class.getName()).log(Level.SEVERE, null, ex);
            }
            LottoAppModel.model = new LottoAppModel();
            return LottoAppModel.model;
        }
        Serializer serializer = new Persister();
        LottoAppModel model=null;
        try {
            model = serializer.read(LottoAppModel.class, file);
        } catch (Exception ex) {
            Logger.getLogger(LottoAppModel.class.getName()).log(Level.SEVERE, null, ex);
        }
        LottoAppModel.model=model;
        return model;
    }
    static void save() throws Exception{
        save(model);
    }
    static void save(LottoAppModel saveMe) throws Exception {
        Serializer serializer = new Persister();
        serializer.write(saveMe, file);
    }

    public void addPlayer(Player player) {
       players.add(player);
    }

    public void addResult(LottoResult lotto) {
        result.add(lotto);
    }
}
